package com.xrit.sunnyday.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.xrit.sunnyday.constant.MessageConstant;
import com.xrit.sunnyday.entity.Result;
import com.xrit.sunnyday.pojo.Menu;
import com.xrit.sunnyday.pojo.Role;
import com.xrit.sunnyday.service.MenuService;
import com.xrit.sunnyday.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/menu")
public class MenuController {
    @Reference
    private UserService userService;

    @Reference
    private MenuService menuService;

    @GetMapping("/getmenu")
    public Result getmenu(){
        //从SECURITY中拿到登录的用户名
        User user = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = user.getUsername();
        //根据用户名查询角色
        com.xrit.sunnyday.pojo.User userInDb = userService.findByUserName(username);
        //取出角色
        Set<Role> roles = userInDb.getRoles();

        //创建存储动态菜单的集合
        List<Menu> menuList = null;
        //遍历角色集合，根据角色ID查询菜单
        for (Role role : roles) {
            menuList = menuService.getmenu(role.getId());
        }

        return new Result(true, MessageConstant.GET_MENU_SUCCESS,menuList);
    }
}
